package cn.com.wxd.biz.user;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.biz.log.AccessLogService;
import cn.com.wxd.dao.user.AccountDao;
import cn.com.wxd.dao.user.UsersDao;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.user.UsersInfo;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.PageInfo;
import cn.com.wxd.util.RequestUtil;
import cn.com.wxd.util.dao.QueryParamHeper;
import cn.com.wxd.common.data.KVMap;
import cn.com.wxd.common.security.PasswordUtil;
import cn.com.wxd.util.user.AccountType;
import cn.com.wxd.util.user.UserCoreUtil;

/**
 * Title:用户信息业务处理类
 * Description:用户信息业务处理类
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2015年10月22日 下午2:39:46
 *
 * @author WangXuDong
 * @version 1.0
 */
public class UsersServiceImpl implements UsersService {
    private static final Logger log = LoggerFactory.getLogger(UsersServiceImpl.class);
    private UsersDao usersDao;
    private AccountDao accountDao;
    private AccessLogService accessLogService;

    /**
     * 登录方法，返回false说明登录失败，否则成功
     * passWord 为使用base64加密密码, ip用户登录地Ip
     */
    @Override
    public boolean login(HttpServletRequest request, String userName, String passWord) {
        String ip = RequestUtil.getRemortIP(request);
        AccountInfo accountInfo = accountDao.selectAccountByUserName(userName); // 获取用户账号信息
        UsersInfo ui = accountInfo.getUsersInfo();
        String passwordStr = PasswordUtil.decipBase64(passWord);  //将base64密码解密成明文密码
        if (ui != null) { //判断用户是否存在
            if (ui.getIsDisabled().equalsIgnoreCase("Y")) {  //用户被禁用
                return false;
            }
            //需要验证密码
            if (PasswordUtil.verify(passwordStr, ui.getPassWord())) { //判断密码是否正确
                if (!updateLoginInfo(accountInfo.getUserName(), ip)) {
                    log.warn("用户：" + accountInfo.getUserName() + ",登录IP和时间没有更新！");
                }
                UserCoreUtil.setLoginUser(request, accountInfo);    //登录用户
                accessLogService.addUserLog(accountInfo, "LOGIN");  //增加登录日志
                return true;
            }
        }
        return false;
    }

    @Override
    public AccountInfo queryAccount(String userName) {
        return accountDao.selectAccountByUserName(userName);
    }

    /**
     * 使用用户名查询用户是否存在以及此号是否被绑定
     */
    @Override
    public boolean queryUserB(String userName) {
        return accountDao.selectAccountByUserName(userName) != null;
    }

    @Override
    public List<AccountInfo> queryAccountByUserId(long userId) {
        return accountDao.selectAccountByuId(userId);
    }

    @Override
    public List<UsersInfo> queryUsersInfos(HashMap<String, String> param) {
        return usersDao.selectUsersInfos(param);
    }

    @Override
    public List<AccountInfo> queryAccountInfos(HashMap<String, String> param) {
        return accountDao.selectAccountInfos(param);
    }

    /**
     * 添加一个用户，用户的密码为使用base64加密的密码
     */
    @Override
    public boolean addUser(AccountInfo accountInfo) {
        //将base64密码解密在加密成加盐的MD5
        UsersInfo usersInfo = accountInfo.getUsersInfo();
        String password = PasswordUtil.generate(PasswordUtil.decipBase64(usersInfo.getPassWord()));
        usersInfo.setPassWord(password);
        accountDao.insertAccount(accountInfo);
        return true;
    }

    /**
     * 更新用户基本信息
     */
    @Override
    public boolean updateBaseUserInfo(String userName, HashMap<String, Object> param) {
        AccountInfo accountInfo = accountDao.selectAccountByUserName(userName);
        UsersInfo ui = accountInfo.getUsersInfo();
        if (ui != null) {
            return usersDao.updateUserInfo(ui.getId(), param);
        }
        return false;
    }

    @Override
    public boolean updateRoles(long userId, String roles) {
        HashMap<String,Object> param = new HashMap<>();
        param.put("roles",roles);
        return usersDao.updateUserInfo(userId, param);
    }

    /**
     * 修改密码
     */
    @Override
    public boolean updatePassword(String userName, String password) {
        String repass = PasswordUtil.decipBase64(password);
        AccountInfo accountInfo = accountDao.selectAccountByUserName(userName);
        if (accountInfo == null) {
            return false;
        }
        return usersDao.updatePassword(accountInfo.getUid(), PasswordUtil.generate(repass));
    }

    /**
     * 获取用户根据时间排序
     */
    @Override
    public List<AccountInfo> queryAllAccountListOrderCTime(int maxCount) {
        PageInfo page = new PageInfo();
        page.setPageIndex(1);
        page.setPageSize(maxCount);
        KVMap<String, String> order = new KVMap<>();
        order.put("lalogTime", QueryParamHeper.DESC);
        return accountDao.selectAccounts(null, order, null, page);
    }

    @Override
    public boolean updateLoginInfo(String userName, String ip) {
        accountDao.updateAccountIp(userName, ip);
        return true;
    }

    /**
     * 获取用户数量
     */
    @Override
    public int getUserCount() {
        return usersDao.selectUserCount();
    }

    /**
     * 用户登录权限修改
     */
    @Override
    public boolean userLoginAuthority(String userName, boolean isForbidden) {
        accountDao.loginAuthority(userName, isForbidden);
        return true;
    }

    /**
     * 绑定用户手机或邮箱
     */
    @Override
    public boolean bindingUserSecurityInfo(String userName, String type, String secInfo) {
        AccountInfo accountInfo;
        if (type.equalsIgnoreCase(AccountType.PHONE) || type.equalsIgnoreCase(AccountType.EMAIL)) {
            //判断该号码是否绑定过了
            accountInfo = accountDao.selectAccountByUserName(secInfo);
            if (accountInfo == null) {
                AccountInfo oldaccountInfo = accountDao.selectAccountByUserName(userName);
                accountInfo.setUserName(secInfo);
                accountInfo.setUid(oldaccountInfo.getUid());
                accountInfo.setLalogTime(oldaccountInfo.getLalogTime());
                accountInfo.setLalogIp(oldaccountInfo.getLalogIp());
                accountInfo.setType(type);
                accountInfo.setCreateTime(DateUtil.getDatetimeStr());
                accountDao.insertAccount(accountInfo);
                return true;
            }
        }
        return false;
    }

    /**
     * 解除用户的绑定
     */
    @Override
    public boolean unwrapUserSecurityInfo(String userName, String type, String secInfoStr) {
        AccountInfo accountInfo;
        if (type.equalsIgnoreCase(AccountType.PHONE) || type.equalsIgnoreCase(AccountType.EMAIL)) {
            accountInfo = accountDao.selectAccountByUserName(secInfoStr);
            if (accountInfo == null) {
                return false;
            }
            List<AccountInfo> accountInfos = accountInfo.getUsersInfo().getAccountInfos();
            if (accountInfos.size() < 2) {
                // 这是唯一的账号无法解绑
                return false;
            }
            // 解绑账号，删除该记录
            accountDao.deleteAccount(userName); // 禁用账号
            return true;
        }
        return false;
    }

    public void setUsersDao(UsersDao usersDao) {
        this.usersDao = usersDao;
    }

    public void setAccessLogService(AccessLogService accessLogService) {
        this.accessLogService = accessLogService;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
}
